package com.mvc.utils;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import com.mvc.annotation.Controller;
import com.mvc.annotation.RequestMapping;
import com.mvc.container.SpringContainer;

public class XmlUtils {
	public XmlUtils() {
	}

	public static List<SpringContainer> simpleXml(String xmlPath) throws Exception {
		List<SpringContainer> rlist = new ArrayList<SpringContainer>();
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlPath));
		Element root = document.getRootElement();
		Element scannerNode = root.getChild("scanner");
		Element packageNode = scannerNode.getChild("package");
		String packageValue = packageNode.getValue();
		String requestUrl = "";
		try {
			List<Class<?>> list = ScannerUtil.getClasses(packageValue);
			for (Class<?> clazz : list) {
				Controller controller = clazz.getAnnotation(Controller.class);
				if (controller != null) {
					RequestMapping classMapping = clazz.getAnnotation(RequestMapping.class);
					Method[] methods = clazz.getMethods();
					for (Method method : methods) {
						RequestMapping methodMapping = method.getAnnotation(RequestMapping.class);
						if (methodMapping != null) {
							requestUrl = classMapping.value() + "/" + methodMapping.value();
							SpringContainer springContainer = new SpringContainer();
							springContainer.setUrl(requestUrl);
							springContainer.setClassName(clazz.getName());
							springContainer.setMethodName(method.getName());
							Parameter[] parameters = method.getParameters();
							if (parameters.length > 0) {
								springContainer.setEntityName(parameters[0].getParameterizedType().getTypeName());
							}
							rlist.add(springContainer);
						}
					}
				} else {
					System.err.println("==============" + clazz.getName() + "类不是Controller==============");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return rlist;
	}
}
